<template>
    <Dialog :app-dialog="appDialog">
        <div class="gc-header">
            <ZwSearchForm ref="searchRef" row-num="3" :option="searchOption" @search="search" @reset="reset" />
            <el-table
                ref="tableRef"
                :data="tableData"
                stripe
                height="480"
                style="width: 100%"
                row-key="id"
                header-row-class-name="table_header_title"
                @select-all="onTableSelectAll"
                @cell-click="onCellClick">
                <el-table-column reserve-selection type="selection" width="55">
                    <template #default="{ row }">
                        <div @click.stop>
                            <el-tooltip
                                class="box-item"
                                effect="dark"
                                :content="onSelectDisableTips(row)"
                                placement="top"
                                trigger="click"
                                :disabled="!onSelectable(row)">
                                <el-checkbox
                                    v-model="row.checkbox"
                                    :disabled="onSelectable(row)"
                                    label=""
                                    size="large"
                                    @change="onCheckBoxChange(row, $event)" />
                            </el-tooltip>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column prop="name" label="群名称" min-width="220">
                    <template #default="scope">
                        <div style="display: flex; align-items: center">
                            <img
                                width="36"
                                height="36"
                                style="border-radius: 4px"
                                :src="scope.row?.avatar ? scope.row?.avatar : '@/assets/customer/group_avatar.png'"
                                alt="" />
                            <span style="margin-left: 10px; font-size: 14px; color: #33302d">{{
                                scope.row?.name
                            }}</span>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column prop="manager" label="群主" min-width="220">
                    <template #default="scope">
                        <div>
                            <div v-show="scope.row.manager?.name">
                                <span v-show="scope.row.manager?.name"> {{ scope.row.manager?.name }}/</span>
                                <span v-show="!scope.row.manager?.name">-/</span>
                                <span v-for="(item, index) in scope.row.manager?.department_name" :key="index">
                                    {{ item.name ? item.name : '-' }}
                                </span>
                            </div>
                            <div v-show="!scope.row.manager?.name">暂无</div>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column prop="members_num" label="群成员" min-width="160"></el-table-column>
                <el-table-column prop="create_type_text" label="创建方式" min-width="200"></el-table-column>
                <el-table-column prop="created_at" label="创建时间" min-width="200"></el-table-column>
            </el-table>
            <div>
                <el-pagination
                    class="pagination"
                    layout="total, prev, pager, next, sizes"
                    align="right"
                    background
                    :total="page.total"
                    :page-size="page.pageSize"
                    :page-sizes="[15, 25, 50, 100]"
                    :current-page="page.page"
                    @size-change="changeSizeHandler"
                    @current-change="changePageHandler">
                </el-pagination>
            </div>
        </div>
    </Dialog>
</template>
<script setup lang="tsx">
import ZwSearchForm from '@/components/zw/search-form/SearchForm';
import Dialog from '@/components/Dialog.vue';

import { ElMessageBox } from 'element-plus';
import { WarningFilled } from '@element-plus/icons-vue';
import { cloneDeep } from 'lodash';

import { deepCopy } from '@/utils/helper';
import { ref, reactive, watch, nextTick, computed, markRaw } from 'vue';

import { getGroupManageList } from '@/api/groupManageList';
import { openSessionList } from '@/api/smartMarketing/community/communityCheckIn';

const emits = defineEmits(['submit', 'save']);

const props = defineProps({
    type: {
        type: String,
        default: 'new'
    },
    isDisabledName: {
        // 是禁用未设置群名,默认true
        type: Boolean,
        default: true
    }
});

const tableRef: any = ref(null);
const searchRef: any = ref(null);

const page = reactive({
    page: 1,
    pageSize: 15,
    total: 0
});

/**
 * 选中数据
 */
const selectList = ref<any>([]);

const tableData = ref([]);

const defaultParams = reactive({
    is_qw_group: 1,
    group_leader: [],
    group_name: ''
});
const state = reactive({
    searchParams: deepCopy(defaultParams)
});
const searchOption = computed(() => {
    return [
        {
            label: '群聊名称',
            name: 'group_name',
            value: '',
            type: 'input',
            width: '280px',
            placeholder: '请输入群聊名称'
        },
        {
            label: '群主/创建人',
            name: 'group_leader',
            value: [],
            type: 'select',
            placeholder: '全部',
            multiple: true,
            popperClass: 'zw-hide_select_option',
            isUserSelect: true,
            formatOption: v => ({
                label: v.name,
                value: v.id
            })
        }
    ];
});

const search = (data: any) => {
    // selectList.value = [];
    // tableRef.value.clearSelection();
    const res = { ...defaultParams, ...data };
    state.searchParams = res;
    initData();
};
const reset = (v?: any) => {
    // selectList.value = [];
    // tableRef.value.clearSelection();
    const res = { ...defaultParams, ...v };
    state.searchParams = res;
    initData();
};

const changePageHandler = (pageNum: any) => {
    page.page = pageNum;
    initData();
};

const changeSizeHandler = (pageSize: any) => {
    page.pageSize = pageSize;
    initData();
};

/**
 * 是否开通会话存档：1开通，并且设置群名
 * @param row
 */
const onSelectable = (row: any) => {
    if (props.isDisabledName) {
        return row.is_open_session_archive != 1 || !row.name || row.name == '未设置群名';
    } else {
        return row.is_open_session_archive != 1;
    }
};

/**
 * 展示tips内容
 * @param row
 */
const onSelectDisableTips = (row: any) => {
    if (row.is_open_session_archive != 1) {
        return '只能选择群内员工有开通会话存档的群聊';
    }
    if (props.isDisabledName && (!row.name || row.name == '未设置群名')) {
        return '只能选择有群聊名称的群聊';
    }
};

/**
 * table全选与全反选
 * @param selection 选中表格数据
 */
const onTableSelectAll = (selection: any) => {
    if (!selection.length) {
        const list: any = [];
        tableData.value.map((el: any) => {
            if (!onSelectable(el)) {
                el.checkbox = false;
                tableRef.value.toggleRowSelection(el, false);
            }
        });
        selectList.value.map((el: any) => {
            if (tableData.value.every(i => i.id != el.id)) {
                list.push(el);
            }
        });
        selectList.value = cloneDeep(list);
    } else {
        tableData.value.map((el: any) => {
            if (!onSelectable(el)) {
                if (selection.every((i: any) => i.id != el.id)) {
                    el.checkbox = false;
                } else {
                    el.checkbox = true;
                }
            }
        });
        selectList.value.map((el: any) => (el.checkbox = true));
        const list = [...selection, ...selectList.value];
        const obj = {};
        let reduce = [];
        reduce = list.reduce((item, next) => {
            obj[next.id] ? '' : (obj[next.id] = true && item.push(next));
            return item;
        }, []);
        selectList.value = reduce.filter((el: any) => el.checkbox);
    }
};

/**
 * 点击一整行选中数据
 * @param row 行数据
 */
const onCellClick = (row: any) => {
    if (props.isDisabledName && (row.is_open_session_archive != 1 || !row.name || row.name == '未设置群名')) {
        return;
    } else if (row.is_open_session_archive != 1) {
        return;
    }
    row.checkbox = !row.checkbox;
    onCheckBoxChange(row, row.checkbox);
};

/**
 * 单条数据选择/取消
 * @param row 选中/取消数据
 * @param select 选中-true，取消-false
 */
const onCheckBoxChange = (row: any, select: any) => {
    tableRef.value.toggleRowSelection(row, select);
    if (select) {
        selectList.value.unshift(row);
    } else {
        const index = selectList.value.findIndex(el => el.id == row.id);
        selectList.value.splice(index, 1);
    }
};

/**
 * 校验
 */
const onCheck = async () => {
    let list: any = [];
    let list2: any = [];

    if (props.type == 'new') {
        list = selectList.value.filter((el: any) => el.is_open_session_archive != 1) || [];
        if (props.isDisabledName) {
            list2 = selectList.value.filter((el: any) => !el.name || el.name == '未设置群名') || [];
        }
    }
    if (props.type == 'edit') {
        const params = {
            groupchat_ids: selectList.value.map(el => el.id)
        };
        const res = await openSessionList(params);
        list = res?.filter((el: any) => el.is_open_session_archive != 1 || el.is_delete == 1) || [];
        if (props.isDisabledName) {
            list2 = res?.filter((el: any) => !el.name || el.name == '未设置群名') || [];
        }
    }
    if (list.length) {
        const text = `你所选择的${selectList.value.length}个群聊中，有${list.length}个群聊未开启会话存档或已解散，系统将自动为你取消选择`;
        await ElMessageBox.confirm(text, '提示', {
            customClass: 'community-checkin-msg-box-confirm',
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
            icon: markRaw(WarningFilled)
        });
        if (props.type == 'new') {
            selectList.value = selectList.value.filter((el: any) => el.is_open_session_archive == 1);
        }
        if (props.type == 'edit') {
            selectList.value = selectList.value.filter((el: any) => list.every(i => i.id != el.id));
        }
    }
    if (list2.length) {
        const text = `你所选择的${selectList.value.length}个群聊中，有${list2.length}个群聊未设置群名，系统将自动为你取消选择`;
        await ElMessageBox.confirm(text, '提示', {
            customClass: 'community-checkin-msg-box-confirm',
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
            icon: markRaw(WarningFilled)
        });
        if (props.type == 'new') {
            selectList.value = selectList.value.filter((el: any) => el.name && el.name != '未设置群名');
        }
        if (props.type == 'edit') {
            selectList.value = selectList.value.filter((el: any) => list2.every(i => i.id != el.id));
        }
    }
    return true;
};

/**
 * table数据
 */
const initData = async () => {
    const params = {
        ...state.searchParams,
        page: page.page,
        page_size: page.pageSize
    };
    const res = await getGroupManageList(params);
    const list = res.data || [];
    nextTick(() => {
        list.map((el: any) => {
            if (selectList.value.length && selectList.value.some((i: any) => i.id == el.id)) {
                el.checkbox = true;
                tableRef.value.toggleRowSelection(el, true);
            }
        });
    });
    tableData.value = list;
    page.total = res.total || 0;
};

/**
 * 弹框-取消
 */
const cancelHandel = () => {
    selectList.value = [];
    state.searchParams = deepCopy(defaultParams);
    page.page = 1;
    page.pageSize = 15;
    page.total = 0;
    tableRef.value.clearSelection();
    appDialog.visible = false;
};

/**
 * 弹框-确定
 */
const submitHandel = async () => {
    await onCheck();
    emits('submit', selectList.value);
    cancelHandel();
};

const appDialog = reactive({
    visible: false,
    title: '选择群聊',
    width: '1200px',
    append: true,
    cancel: cancelHandel,
    submit: submitHandel,
    cancelText: '取消',
    submitText: '确定'
});

watch(
    () => appDialog.visible,
    val => {
        val && initData();
    }
);

defineExpose({
    appDialog,
    selectList
});
</script>
<style scoped lang="scss">
:deep(.el-radio-group) {
    display: block !important;
}

:deep(.table_header_title) {
    height: 48px;

    th.el-table__cell {
        background: #f9f9f9;
        padding: 10px 0;
    }
}

.hide_All {
    :deep(.el-table__header-wrapper) {
        thead .table_header_title .el-checkbox {
            display: none;
        }
    }
}

.gc-header {
    margin-bottom: 20px;

    .form-inline {
        justify-content: space-between;

        .el-form-item {
            margin-bottom: 0;
            padding: 18px;
        }

        display: flex;
        align-items: center;
    }

    .btn-wrap {
        margin-right: 10px;
    }
}

.emty_img {
    margin-top: 50px;
    transform: translateX(15%);
}

.emty_title {
    margin-top: -50px;
}
</style>
